package spring.chatroom.java_chatroom.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.ProcessInfo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import spring.chatroom.java_chatroom.common.utils.TypeTran;
import spring.chatroom.java_chatroom.pojo.model.MsgInfo;
import spring.chatroom.java_chatroom.server.MesSendServer;
import spring.chatroom.java_chatroom.server.SaveFiles;

import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("save")
public class SaveFilesController {

    @Autowired
    SaveFiles saveFiles;

    @Autowired
    MesSendServer mesSendServer;

    @Autowired
    ObjectMapper objectMapper;

    @RequestMapping("/files")
    public int saveFiles(@NotNull @RequestParam("files") List<MultipartFile> files,
                         @NotNull @RequestParam("sender") String sender ) throws IOException, InterruptedException {
        log.info("saveFile 收到保存文件请求 {}", files);
        List<String> list = saveFiles.saveFiles(files);

        MsgInfo msgInfo = objectMapper.readValue(sender, MsgInfo.class);

        //消息处理逻辑
        //储存消息到数据库
//        log.info("文件储存到消息库中的格式 {}", list);
        List<MsgInfo> msgInfoList = saveFiles.saveToDB(list, msgInfo);

        //发送 WebSession msg
        for (MsgInfo fileName : msgInfoList) {
            mesSendServer.sendMsg(msgInfo);
        }

        return list.size();
    }
}
